<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意：只允许第三级分类设置配置参数" type="warning" :closable="false" show-icon>
      </el-alert>

      <el-row class="ParamsForm">
        <el-col>
          <el-form ref="ParamsFormRef" label-width="100px">
            <el-form-item label="选择商品分类">
              <el-cascader v-model="selectedCateKeys" :options="paramsList" :props="paramsProps" @change="handleChange"
                clearable>
              </el-cascader>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="tabChangeClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnOk" @click="addParamsDialogVisible = true">添加参数
          </el-button>

          <el-table :data="manyDataList" stripe border="" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item ,i) in scope.row.attr_vals" :key="i" closable @close="closeTag(i,scope.row)">
                  {{item}}
                </el-tag>

                <!-- 添加标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit"
                  @click="editParamsDialogShow(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="DeleteParamsData(scope.row.attr_id)">
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnOk" @click="addParamsDialogVisible = true">添加属性
          </el-button>

          <el-table :data="onlyDataList" stripe border="" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item ,i) in scope.row.attr_vals" :key="i" closable @close="closeTag(i,scope.row)">
                  {{item}}
                </el-tag>

                <!-- 添加标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit"
                  @click="editParamsDialogShow(scope.row.attr_id)">修改</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="DeleteParamsData(scope.row.attr_id)">
                  删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog :title="'添加' + titleChoice" :visible.sync="addParamsDialogVisible" width="50%"
      @close="addParamsFormClosed">
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="titleChoice" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类对话框 -->
    <el-dialog :title="'添加' + titleChoice" :visible.sync="editParamsDialogVisible" width="50%"
      @close="editParamsFormClosed">
      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="titleChoice" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      selectedCateKeys: [],
      paramsProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        multiple: false,
        emitPath: false,
        expandTrigger: 'hover'
      },
      paramsList: [],
      activeName: 'many',
      ParamsDataList: [],
      manyDataList: [],
      onlyDataList: [],

      //添加分类对话框属性
      addParamsDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsFormRules: {
        attr_name: { required: true, message: '请输入活动名称', trigger: 'blur' },
      },

      //修改分类对话框属性
      editParamsDialogVisible: false,
      editParamsForm: {
        attr_id: ''
      },
      editParamsFormRules: {
        attr_name: { required: true, message: '请输入活动名称', trigger: 'blur' }
      },
    }
  },
  created () {
    this.getParamsList()
  },
  methods: {
    async getParamsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类')
      this.paramsList = res.data
    },
    // 级联选择器的改变事件
    handleChange () {
      this.getParamsList()
      this.getParamsDataList()
    },
    // 标签页的改变事件
    tabChangeClick () {
      console.log(this.activeName)
      this.getParamsDataList()
    },
    // 获取分类参数列表
    async getParamsDataList () {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status != 200) return
      this.$message.success('获取分类参数成功！')

      if (this.activeName == 'many') {
        this.manyDataList = res.data
      }
      if (this.activeName == 'only') {
        this.onlyDataList = res.data
      }

      console.log(res.data)

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
        item.inputVisible = false
        item.inputValue = ''
      })
    },
    //对话框关闭事件
    addParamsFormClosed () {
      this.$refs.addParamsFormRef.resetFields()
    },
    //对话框确定提交事件
    addParamsBtn () {
      // 预验证
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('添加动态参数或者静态属性失败！')
        this.$message.success('添加动态参数或者静态属性成功')
        this.getParamsDataList()
        this.addParamsDialogVisible = false
      })
    },

    // 修改对话框的显示
    async editParamsDialogShow (attr_id) {

      // 根据 ID 查询参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`)
      if (res.meta.status != 200) return this.$message.error('查询参数失败！')
      this.$message.success('查询参数成功！')
      this.editParamsForm = res.data
      this.editParamsForm.attr_id = attr_id
      this.editParamsDialogVisible = true
    },
    // 修改对话框关闭事件
    editParamsFormClosed () {
      this.$refs.editParamsFormRef.resetFields()
    },

    // 修改对话框确定事件
    editParamsBtn () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('编辑提交参数失败!')
        this.$message.success('编辑提交参数成功！')
        this.getParamsDataList()
        this.editParamsDialogVisible = false
      })
    },
    // 删除按钮的点击事件
    async DeleteParamsData (attr_id) {
      // 弹框确认
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      if (confirmResult == 'cancel') return this.$message({
        type: 'info',
        message: '已取消删除'
      })


      //请求删除操作
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
      console.log(res)
      this.getParamsDataList()
      this.editParamsDialogVisible = false
    },

    // 失去焦点和摁下enter键时触发的事件
    async handleInputConfirm (row) {
      // row.inputVisible = false
      console.log('ok')
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }

      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      console.log(row)
      this.saveAttrInput(row)
    },
    async saveAttrInput (row) {
      // 添加分类属性categories /: id / attributes
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })

      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('添加分类参数失败！')
      this.$message.success('添加分类参数成功！')
    },

    //点击new Tag时显示input
    showInput (row) {
      console.log(row.inputVisible)
      // 不能及时显示
      row.inputVisible = true
    },

    // 删除标签事件
    closeTag (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrInput(row)
    }


  },
  computed: {
    // 根据级联选择器是否有值来判断按钮是否可选
    isBtnOk () {
      if (typeof this.selectedCateKeys == 'object') {
        return true
      } else {
        return false
      }
    },
    // 获取分级id
    cateId () {
      if (typeof this.selectedCateKeys == 'number') {
        return this.selectedCateKeys
      }
      return null
    },
    // 根据tab便签页的名称改变对话框的内容
    titleChoice () {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ParamsForm {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
